layui.define(['jquery'], function (exports) {

    var $ = layui.jquery;

    var readClusterLog = {
        show: function (clusterId, option) {
            this.option = $.extend({
                maxLineSize: 500
            }, option || {});

            var that = this;

            layer.open({
                title: '查看日志',
                type: 1,
                content: `<div style="padding: 20px 20px 0px 20px;"><div id="readClusterLog" class="layui-row">
                <div class="layui-col-xs6">
                    <fieldset class="layui-elem-field">
                    <legend>地表服务</legend>
                    <div class="layui-field-box" id="masterLogBox" style="height: 615px; overflow: scroll; width: 544px;">
                        <pre id="master_log" style="white-space: pre"></pre>
                    </div>
                    </fieldset>
                </div>
                <div class="layui-col-xs6">
                    <fieldset class="layui-elem-field">
                    <legend>洞穴服务</legend>
                    <div class="layui-field-box" id="cavesLogBox" style="height: 615px; overflow: scroll; width: 544px;">
                        <pre id="caves_log" style="white-space: pre"></pre>
                    </div>
                    </fieldset>
                </div></div></div>`,
                area: ['1200px', '800px'],
                btn: ['发送指令', '关闭'],
                btn2: function (index, layero) {
                    layer.close(index);
                },
                yes: function (index, layero) {
                    var cmdHistory = JSON.parse(localStorage.getItem('cmd_history') || '[]');
                    layer.prompt({
                        formType: 2,
                        value: cmdHistory.length ? cmdHistory[cmdHistory.length - 1] : '',
                        title: '请输入指令',
                        area: ['400px', '100px'] //自定义文本域宽高
                    }, function (value, index, elem) {
                        if (!value) return;
                        var loadIndex = layer.load();
                        $.ajax({
                            url: '/api/send_cmd',
                            dataType: 'JSON',
                            type: 'POST',
                            data: {
                                cluster_id: clusterId,
                                cmd_str: value
                            },
                            success: function (data) {
                                // 执行成功的话在执行历史上加一条
                                cmdHistory.push(value);
                                cmdHistory = cmdHistory.slice(-20);
                                localStorage.setItem('cmd_history', JSON.stringify(cmdHistory));

                                layer.close(loadIndex);
                                layer.close(index);

                                layer.msg(data.msg);
                            },
                            error: function () {
                                layer.close(loadIndex);
                                layer.open({
                                    title: '提示',
                                    content: '糟糕，出问题了。'
                                });
                            }
                        });
                    });
                    return false;
                },
                end: function (index, layero) {
                    clearInterval(that.timer);
                }
            });

            var masterLine = 0,
                cavesLine = 0,
                count = 0,
                keeping = false,
                scrollData = {
                    master: {
                        left: 0,
                        top: 0
                    },
                    caves: {
                        left: 0,
                        top: 0
                    }
                };

            loadLog();
            that.timer = setInterval(loadLog, 2000);

            function loadLog() {
                if (count++ > 300) { // 十分钟后直接取消
                    clearInterval(that.timer);
                    layer.open({
                        title: '提示',
                        content: '日志查看超时'
                    });
                    return;
                };
                if (keeping) {
                    return;
                };
                keeping = true;

                // var loadIndex = layer.load();
                $.ajax({
                    url: '/api/load_clusterlog',
                    type: 'POST',
                    dataType: 'JSON',
                    data: {
                        cluster_id: clusterId,
                        masterLine: masterLine,
                        cavesLine: cavesLine
                    },
                    success: function (data) {
                        // layer.close(loadIndex);
                        keeping = false;
                        masterLine = masterLine + data.data.masterLog.split(/\r?\n/).length - 1;
                        cavesLine = cavesLine + data.data.cavesLog.split(/\r?\n/).length - 1;
                        var masterLog = $('#master_log').html() + data.data.masterLog;
                        var cavesLog = $('#caves_log').html() + data.data.cavesLog;

                        tmpArr = masterLog.split(/\r?\n/);
                        masterLog = tmpArr.slice(tmpArr.length - that.option.maxLineSize).join('\r\n');

                        tmpArr = cavesLog.split(/\r?\n/);
                        cavesLog = tmpArr.slice(tmpArr.length - that.option.maxLineSize).join('\r\n');

                        scrollData.master.left = $('#masterLogBox')[0].scrollLeft;
                        scrollData.master.top = $('#masterLogBox')[0].scrollTop;

                        scrollData.caves.left = $('#cavesLogBox')[0].scrollLeft;
                        scrollData.caves.top = $('#cavesLogBox')[0].scrollTop;

                        if (data.data.masterLog) {
                            $('#master_log').html(masterLog);
                            $('#masterLogBox')[0].scrollTo(scrollData.master.left, scrollData.master.top);
                        }

                        if (data.data.cavesLog) {
                            $('#caves_log').html(cavesLog);
                            $('#cavesLogBox')[0].scrollTo(scrollData.caves.left, scrollData.caves.top);
                        }
                    },
                    error: function (xhr, textStatus, errorTh) {
                        keeping = false;
                        clearInterval(that.timer)
                        // layer.close(loadIndex);
                        // layer.open({
                        //     title: '提示',
                        //     content: '糟糕，出问题了。'
                        // });
                    }
                });
            }
        }
    };

    exports('readClusterLog', readClusterLog);
});